/**
 * Created by Jie on 2017/2/7.
 */
var async = require('async');
var db = require('../../util/pool');
var format = require('../../util/json2sql');
var data = require('../../util/result');
var _ = require('underscore');

var Model = function() {};
var _table = 'role_fk_menu';

Model.prototype.auth = function (json,callback) {
    json =  eval('(' + json + ')');
    db.trans(function (err,connection) {
        //console.log('connection',connection);
        connection.beginTransaction(function(err) {
            if (err) {
                callback(err,null);
                return;
            }
            var taskArr = [];
            //数据删除
            var opt = format.opt(_table,' and roleId='+json[0].roleId);
            var task0 = function (callback) {
                connection.query(opt, function(err, result) {
                    if (err) {
                        callback(err,null);
                        return;
                    }
                    callback(null,result);
                });
            }
            taskArr.push(task0);
            //数据添加
            var sql=format.inserts(_table,json);;

            console.log('sql',sql);
            var task = function(callback){
                connection.query(sql, function(err, result) {
                    if (err) {
                        callback(err,null);
                        return;
                    }
                    callback(null,result);
                });
            }
            taskArr.push(task);
            async.series(taskArr,function(err,result){
                if (err) {
                    //回滚
                    connection.rollback(function() {
                        //console.log('出现错误,回滚!');
                        //释放资源
                        connection.release();
                    });
                    callback(err,data.result(1,'异常'));
                    return;
                }
                //提交
                connection.commit(function(err) {
                    if (err) {
                        callback(err,data.result(1,'连接异常'));
                        return;
                    }
                    //释放资源
                    connection.release();
                    callback(err,data.result(0,'分配成功'));
                });
            });
        });
    });
}

Model.prototype.findByRoleId = function (roleId,callback) {
    var sql = format.find(_table,' and roleId='+roleId);
    db.query(sql,function (err,results) {
        if(!err){
            callback(null,data.result(0,'ok',results));
        }else{
            callback(null,data.result(1,'异常'));
        }
    })
}
module.exports = Model;